package gupao.concurrency.threads.aqs;

import gupao.concurrency.threads.Utils;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class Tester {
    static ProductsContainer<Product> container = new ProductsContainer<>(10);
    static AtomicBoolean producerStopFlag = new AtomicBoolean(false);
    static AtomicBoolean consumerStopFlag = new AtomicBoolean(false);

    static long produceTimeCost = 3 * 100; //millis
    static long consumeTimeCost = 50;

    static void setDaemonAndStart(Thread... list){
        for (Thread t : list) {
            t.setDaemon(true);
            t.start();
        }
    }

    public static void main(String[] args){
        Producer p = new Producer(container, producerStopFlag, produceTimeCost, Tester::nextProduct);
        Consumer c = new Consumer(container, consumerStopFlag, consumeTimeCost);

        Thread producerThread = new Thread(p, "p-1");
        Thread producerThread2 = new Thread(p, "p-2");
        Thread producerThread3 = new Thread(p, "p-3");

        Thread consumerThread = new Thread(c, "c-1");
        Thread consumerThread2 = new Thread(c, "c-2");

        setDaemonAndStart(producerThread,producerThread2,producerThread3);

        Utils.sleepIgnoreExp(1000 * 6);

        setDaemonAndStart(consumerThread,consumerThread2);

        while(Thread.activeCount() > 1){
            Thread.yield();
        }
        System.out.println("Completed");
    }

    static AtomicInteger productNum = new AtomicInteger(0);
    static Product nextProduct(){
        int x = productNum.incrementAndGet();
        if( x > 20 ){
            return Product.PILL;
        }
        return new Product(x);
    }

    static void setStop(){
        producerStopFlag.set(true);
        consumerStopFlag.set(true);
    }
}
